package com.systop.asset.utils;

import com.systop.asset.service.Treeable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtils {
    public static <T extends Treeable<T>> List<T> buildTree(List<T> all) {
        Map<Long, T> nodeMap = new HashMap<>();
        all.forEach(item -> nodeMap.put(item.getId(), item));

        List<T> rootNodes = new ArrayList<>();

        for (T node : all) {
            Long parentId = node.getParentId();
            if (parentId == 0 || parentId == null) {
                rootNodes.add(node);
            } else {
                T parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }else{
                    //放行前端带参数的数据
                    rootNodes.add(node);
                }
            }
        }

        return rootNodes;
    }
}

